package com.genericdevice.platform.core.dialog.helpers;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Xilent on 25.05.2014.
 */
public class FileListHelper {
    public static final String FILE_TYPE = "file";
    public static final String FOLDER_TYPE = "folder";
    public static final String TYPE_FIELD = "type";
    public static final String PATH_FIELD = "path";
    public static final String NAME_FIELD = "name";

    public static List<Map<String, String>> getFolderList(String path, final String format) {
        File dir = new File(path);

        String[] list = dir.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                File file = new File(dir.getAbsolutePath() + filename);
                if (file.isFile() && format != null) {
                    if (filename.endsWith("." + format))
                        return true;
                    else
                        return false;
                } else {
                    return true;
                }
            }
        });

        List<Map<String, String>> folderList = new ArrayList<Map<String, String>>();

        if (list == null)
            return folderList;

        for (String filename : list) {
            Map<String, String> folderListEntry = new HashMap<String, String>();
            File type = new File(path + filename);

            if (type.isDirectory())
                folderListEntry.put(TYPE_FIELD, FOLDER_TYPE);
            else
                folderListEntry.put(TYPE_FIELD, FILE_TYPE);

            folderListEntry.put(PATH_FIELD, path + filename + (type.isDirectory() ? File.separator : "" ));
            folderListEntry.put(NAME_FIELD, type.getName() + (type.isDirectory() ? File.separator : "" ));
            folderList.add(folderListEntry);
        }

        return folderList;
    }
}
